<template>
  <section class="works-main">
    <el-collapse-transition>
      <section v-show="searchshow" class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.worksName"
          placeholder="输入作品名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <section class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </section>
      </section>
    </el-collapse-transition>
    <el-collapse-transition>
      <section v-show="!searchshow" class="main-search separate">
        <section class="search-inner">
          <el-row>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">作品名称</div>
                <el-input
                  v-model.trim="search.worksName"
                  style="width: 90%;"
                  class="filter-item"
                  placeholder="请输入作品名称搜索"
                />
              </section>
            </el-col>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">姓名</div>
                <el-input
                  v-model.trim="search.userName"
                  style="width: 90%;"
                  class="filter-item"
                  placeholder="请输入姓名搜索"
                />
              </section>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">证件号码</div>
                <el-input v-model.trim="search.idCard" style="width: 80%" class="filter-item" placeholder="请输入证件号码搜索" />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">手机号码</div>
                <el-input
                  v-model.trim="search.phoneNum"
                  style="width: 80%"
                  class="filter-item"
                  placeholder="请输入手机号码搜索"
                />
              </div>
            </el-col>

          </el-row>
        </section>
        <section class="search-btn">
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </section>
      </section>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>作品管理</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px;" @click="handleCreate">上传作品</el-button>
        <el-button style="margin-left: 10px" @click="handleBack">返回</el-button>
        <!--        <el-button v-if="activeTab === '2'" style="margin-left: 10px;" @click="handleMultiSet">批量设置</el-button>-->
      </section>
    </section>
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in checkList" :key="item.id" :label="item.name" :name="item.id" />
      </el-tabs>
    </div>
    <section class="main-table">
      <v-table
        :list="list"
        :tag="'worksManage' + activeTab"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
        :selection="false"
      >
        <el-table-column label="操作" fixed="right" align="center" min-width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="activeTab === '1'" type="text" size="mini" @click="handleCheck(scope.row)">审核作品</el-button>
            <el-button v-else type="text" size="mini" @click="handleView(scope.row)">查看作品</el-button>
            <el-button
              v-if="activeTab === '2' || activeTab === '5'"
              type="text"
              size="mini"
              @click="handlePublish(scope.row)"
            >
              {{ scope.row.isOff === 0 ? '下架' : '上架' }}
            </el-button>
            <el-button
              v-if="activeTab === '2' || activeTab === '4' || activeTab === '5'"
              type="text"
              size="mini"
              @click="handleRecommend(scope.row)"
            >
              {{ scope.row.isRecommend === 0 ? '推荐' : '取消推荐' }}
            </el-button>
            <el-button
              v-if="activeTab === '2' || activeTab === '4' || activeTab === '5'"
              type="text"
              size="mini"
              @click="handleReject(scope.row)"
            >驳回
            </el-button>
            <el-button
              v-if="activeTab === '2' || activeTab === '4' || activeTab === '5'"
              type="text"
              size="mini"
              @click="handleSet(scope.row)"
            >设置
            </el-button>
            <el-button v-if="activeTab === '3'" type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-if="activeTab === '2' || activeTab === '4' || activeTab === '5'" type="text" size="mini" @click="handleComment(scope.row.id)">查看评论</el-button>
          </template>
        </el-table-column>
      </v-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
      <news-set
        v-if="newsSetStatus"
        :id="newsItem.id"
        :obj="newsItem"
        :type="setType"
        @closeSet="newsSetStatus = false, getList()"
      />
      <!--驳回弹框      -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        center
        @close="closeDialog"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="审核说明" prop="auditRemark">
            <el-input v-model="form.auditRemark" type="textarea" />
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submitReject">确 定</el-button>
        </span>
      </el-dialog>
    </section>
    <works-preview v-if="worksPreviewStatus" :id="worksId" :works-type="activeTab" @closeSet="worksPreviewStatus = false" />
  </section>
</template>
<script>
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import { queryPage, updateState, recommend, queryAuditedPage, audit, getMaxSort } from '../api/works'
import permission from '@/directive/permission/index.js'
import NewsSet from '../components/NewsSet'
import CryptoJS from '@/utils/aesJiaJM'
import WorksPreview from '../components/WorksPreview'

export default {
  name: 'WorksManage',
  components: { Pagination, VTable, NewsSet, WorksPreview },
  directives: { permission },
  data() {
    return {
      searchshow: true,
      listQuery: {
        page: 1,
        limit: 10,
        worksName: ''
      },
      search: {
        worksName: '',
        userName: '',
        phoneNum: '',
        idCard: ''
      },
      activeTab: '1',
      checkList: [
        {
          name: '待审核',
          id: '1'
        }, {
          name: '已审核',
          id: '2'
        },
        {
          name: '已推荐',
          id: '4'
        }, {
          name: '最热',
          id: '5'
        }, {
          name: '已驳回',
          id: '3'
        }
      ],
      list: [],
      total: 0,
      listLoading: false,
      view: '/API-DOCUMENT/file/download/',
      newsSetStatus: false,
      newsItem: {},
      setType: 'single',
      id: '',
      worksId: '',
      worksPreviewStatus: false,
      // 审核弹框
      dialogVisible: false,
      form: {
        id: '',
        auditRemark: ''
      },
      rules: {
        auditRemark: [
          { required: true, message: '请输入审核说明', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    if (!this.$route.query.i) {
      this.$message({
        showClose: true,
        message: '参数异常！',
        type: 'warning',
        onClose: () => {
          this.$router.back()
        }
      })
      return
    }
    this.activeTab = this.$route.query.tab || '1'
    this.id = this.$route.query.i
    this.getList()
  },
  methods: {
    handleBack() {
      this.$router.back()
    },
    /**
     * 选项卡切换
     */
    handleTabClick() {
      this.listQuery.page = 1
      this.getList()
    },
    filtercolumn(scope, item) {
      if (item === 'authorPhoneNumber' || item === 'authorIdNumber') {
        return scope.row[item] ? CryptoJS.$aesJieM(scope.row[item]) : '--'
      } else {
        return scope.row[item]
      }
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.userRealName = ''
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: this.$filterPath('worksCreate'), query: { pi: this.$route.query.i }})
    },
    handleCheck(row) {
      this.$router.push({ path: this.$filterPath('worksCheck'), query: { i: row.id, t: this.activeTab, pi: this.$route.query.i }})
    },

    handleView(row) {
      this.worksId = row.id
      this.worksPreviewStatus = true
    },
    /**
     * 上架 下架
     */
    handlePublish(row) {
      this.$confirm(row.isOff === 0 ? '确认下架作品？' : '确认上架作品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateState({ id: row.id, isOff: row.isOff === 0 ? 1 : 0 }).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {

      })
    },
    /**
     * 批量设置
     */
    handleMultiSet() {
      this.setType = 'multi'
      this.newsSetStatus = true
    },
    /**
     * 修改
     */
    handleUpdate(row) {
      this.$router.push({
        path: this.$filterPath('worksCreate'),
        query: { pi: this.$route.query.i, i: row.id, type: 'u' }
      })
    },
    /**
     * 查看评论
     */
    handleComment(id) {
      this.$router.push({ path: this.$filterPath('worksComment'), query: { i: id, t: this.activeTab, pi: this.$route.query.i }})
    },
    /**
     * 单个设置
     */
    handleSet(row) {
      this.setType = 'single'
      this.newsItem = Object.assign({}, row)
      this.newsSetStatus = true
    },
    /**
     * 已审核的---驳回
     * */
    handleReject(row) {
      // this.$router.push({ path: this.$filterPath('worksCheck'), query: { i: row.id, t: 'reject' }})
      this.form.id = row.id
      this.dialogVisible = true
    },
    /**
     * 关闭驳回作品弹框
     * */
    closeDialog() {
      this.dialogVisible = false
      for (const i in this.form) {
        this.form[i] = ''
      }
    },
    /**
     * 提交 驳回作品
     * */
    submitReject() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            audit({
              id: this.form.id,
              auditResult: 'AUDITRESULT04',
              auditRemark: this.form.auditRemark
            }).then(res => {
              loading.close()
              this.$message({
                title: '成功',
                message: '审核成功',
                type: 'success',
                duration: 1000
              })
              this.closeDialog()
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      }
      )
    },
    /**
     * 推荐/取消推荐
     * @param row
     */
    async handleRecommend(row) {
      if (row.isRecommend === 0) {
        const sortValue = await this.getMaxSort()
        console.log(sortValue)
        this.$prompt('请输入推荐排序(值越大，越靠前)', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: +sortValue,
          inputPattern: /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/,
          inputErrorMessage: '请输入数字'
        }).then(({ value }) => {
          return new Promise((resolve, reject) => {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })

            recommend({ id: row.id, isRecommend: 1, recommendSort: value }).then((res) => {
              loading.close()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消推荐'
          })
        })
      } else {
        this.$confirm('确认取消推荐？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          recommend({ id: row.id, isRecommend: 0 }).then(res => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            }
          })
        }).catch(() => {

        })
      }
    },
    getMaxSort() {
      return new Promise((resolve, reject) => {
        getMaxSort({ solicitationId: this.id }).then(res => {
          resolve(res.data.data)
        }).catch(() => {
          resolve('')
        })
      })
    },
    getList(obj) {
      this.listLoading = true
      const query = {
        solicitationId: this.id,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        auditResult: this.activeTab === '1' ? 'AUDITRESULT01' : this.activeTab === '3' ? 'AUDITRESULT03' : ''
      }
      if (this.activeTab === '5' || this.activeTab === '4') {
        query['type'] = this.activeTab === '4' ? 3 : 2
      }
      if (this.searchshow) {
        query['worksName'] = this.listQuery.worksName
      } else {
        query['worksName'] = this.search.worksName
        query['authorRealName'] = this.search.userName
        query['authorPhoneNumber'] = CryptoJS.$aesJiaM(this.search.phoneNum)
        query['authorIdNumber'] = CryptoJS.$aesJiaM(this.search.idCard)
      }
      if (this.activeTab === '2' || this.activeTab === '5' || this.activeTab === '4') {
        return new Promise((resolve, reject) => {
          queryAuditedPage(query).then(response => {
            this.list = response.data.data.rows
            this.total = response.data.data.total
            this.listLoading = false
          }).catch(error => {
            reject(error)
            this.listLoading = false
          })
        })
      } else {
        return new Promise((resolve, reject) => {
          queryPage(query).then(response => {
            this.list = response.data.data.rows
            this.total = response.data.data.total
            this.listLoading = false
          }).catch(error => {
            reject(error)
            this.listLoading = false
          })
        })
      }
    }
  }
}
</script>
<style lang="scss">

.works-main {
  padding: 10px;

  .main-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            &.el-date-editor input {
              padding-left: 30px;
            }

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    padding: 0 10px;
    background-color: #fff;
    display: flex;
    border-radius: 4px;

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__header {
      margin: 0;
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>
